<?php
// No direct access
defined ('_JEXEC') or die();

jimport ('joomla.application.component.modeladmin');

class ShipnhanhModelContactInfo extends JModelAdmin
{
	private $columns = array('name', 'email', 'address', 'phone');
	
	public function getForm($data = array(), $loadData = true)
	{
		// Get form
		$form = $this->loadForm('com_shipnhanh.contactinfo', 'contactinfo', array('control' => 'jform', 'load_data' => $loadData));
	
		if (! $form)
		{
			return false;
		}
		else
		{
			return $form;
		}
	}
	
	public function loadFormData()
	{
		$data = $this->getItem();
	
		return $data;
	}
	
	public function findContactByEmail($email = null)
	{
		if (!isset($email))
			return -1;
		
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		
		$query->select('id');
		$query->from('#__sn_contact_info');
		$search  = $db->quote($db->escape($email, true));
		$query->where('email = ' . $search);
		
		$db->setQuery($query);
		$id = $db->loadResult();
		
		return $id;
	}
	
	public function getContactById($id)
	{
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		
		$query->select('id, email, address, phone, name');
		$query->from('#__sn_contact_info');
		$query->where('id = ' . $id);
		
		$db->setQuery($query);
		
		return $db->loadObject();
	}
	
	public function insertContactInfo($name = null, $email = null, $address = null, $phone = null)
	{
		if (!isset($email))
			return -1;
		
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$values = array($db->quote($name), $db->quote($email), $db->quote($address), $db->quote($phone));
		
		$query->insert('#__sn_contact_info');
		$query->columns($this->columns);
		$query->values(implode(',', $values));
		$db->setQuery($query);
		$db->query();
		
		return $db->insertid();
	}
	
	public function updateContactInfo($id, $name = null, $email = null, $address = null, $phone = null)
	{
		if (!isset($email))
			return -1;
		
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		$fields = array('email=' . $db->quote($email),
				'address=' . $db->quote($address),
				'phone=' . $db->quote($phone),
				'name=' . $db->quote($name));
		
		$query->update('#__sn_contact_info');
		$query->set($fields);
		$query->where('id=' . $id);
		$db->setQuery($query);
		$db->query();
	}
	
}